package com.demo.gateway.utils;

/**
 * @author yzy
 * @date 2024/7/13 下午6:19
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

public class JsonAssembleUtils extends AssembleUtils {

    @Override
    protected Map<String, Object> parseData(String dataString) {
        JSONObject jsonObject = JSON.parseObject(dataString);
        return jsonObject.getInnerMap();
    }

    @Override
    protected String replacePlaceholders(String template, String key, Object value) {
        if (value instanceof Map) {
            Map<String, Object> valueMap = (Map<String, Object>) value;
            for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
                String subKey = entry.getKey();
                Object subValue = entry.getValue();
                template = replacePlaceholders(template, key + "." + subKey, subValue);
            }
        } else if (value instanceof String) {
            template = template.replace("${" + key + "}", "\"" + value + "\"");
        } else if (value instanceof Boolean || value instanceof Number) {
            template = template.replace("${" + key + "}", String.valueOf(value));
        } else if (value instanceof Iterable) {
            template = template.replace("${" + key + "}", JSON.toJSONString(value));
        }

        return template;
    }
}
